<?php

namespace app\index\service;

use app\common\model\ConsultingForm;
use app\common\service\ARYPushQueueService;
use app\index\dao\ConsultingFormDao;
use app\index\model\UM as UM;
use ShidianUtil\Utils\CheckUtil;
use think\exception\ValidateException;

/**
 * Class ConsultingFormService
 * @package app\index\service
 */
class ConsultingFormService
{
    // dao
    private ConsultingFormDao $consultingFormDao;

    public function __construct(ConsultingFormDao $consultingFormDao)
    {
        $this->consultingFormDao = $consultingFormDao;
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  ConsultingForm
     */
    public function add(UM $user, array $params): ConsultingForm
    {
        $consultingFormType = $params['consultingFormType'] ?? ConsultingForm::TYPE_FORM1;
        $memberId = $user->id;
        $phone = $params['phone'] ?? $user->phone;
        $categoryId = $params['categoryId'] ?? null;
        $details = $params['details'] ?? [];
        $detailsValid = details_valid($details);

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if ($consultingFormType == ConsultingForm::TYPE_FORM1) {
            if (!CheckUtil::isPhoneNumber($phone)) {
                throw new ValidateException('请输入电话号码');
            }
            if (!is_id($categoryId)) {
                throw new ValidateException('请选择一个案件类型');
            }
        }

        // 添加咨询表单记录
        $data = [
            'consultingFormType' => $consultingFormType,
            'memberId' => $memberId,
            'categoryId' => $categoryId,
            'phone' => $phone,
            'status' => 0,
            'details' => $details,
            'detailsValid' => $detailsValid,
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
        ];
        $record = $this->consultingFormDao->insertActive($data, []);

        // 延迟到案如云
        if ($consultingFormType == ConsultingForm::TYPE_FORM1) {
            $this->getARYPushQueueService()->pushConsultingForm($record->id);
        }

        return $record;
    }

    private function getARYPushQueueService(): ARYPushQueueService
    {
        return app(ARYPushQueueService::class);
    }

}
